package com.itheima.quartz;

import com.itheima.mapper.MemberMapper;
import com.itheima.utils.QiniuUtils;
import com.itheima.constant.RedisConstant;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.stereotype.Component;
import redis.clients.jedis.Jedis;
import redis.clients.jedis.JedisPool;

import java.text.SimpleDateFormat;
import java.util.*;

/**
 * 清理垃圾图片的定时任务
 */
@ComponentScan(basePackages = "com.example.springboot.mapper")
@Component
public class ClearImgQuartz {


    @Autowired
    private MemberMapper memberMapper;

    public  void clearDate(){
        try {
            List<String> yearAndMoth = new ArrayList<>();

            //获取日历对象
            Calendar calendar = Calendar.getInstance();
            //设置日历往前推2个月的缓存数据
            calendar.add(Calendar.MONTH, -2);
            List list = new ArrayList();
            for (int i = 0; i < 12; i++) {
                //获取每个月的时间
                Date time = calendar.getTime();
                //获取每个月的月份
                String month = new SimpleDateFormat("yyyy-MM").format(time);
                // 转换好日期之后  将我们需要的 xxxx年xx月 +“1”  和  xxxx年xx月 +“31”
                String beginDate = month+"-1";
                String endDate = month+"-31";
                // 查询 每个月的会员数量   查询的Sql语句条件 就是 beginDate  ；  endDate
                // 每次获得一个月份 都-1
                calendar.add(Calendar.MONTH, -1);
                // 直接执行删除sql 的语句
                /*  beginDate="2020-07-05";*/
                /*     memberMapper.DeleteMenberCountsByDate(beginDate);*/
                memberMapper.DeleteMenberCountsByDate(beginDate,endDate);
                //将得到的月份添加到年月的List集合中去
                yearAndMoth.add(month);
            }
            System.out.println(yearAndMoth);

        } catch (Exception e) {
            e.printStackTrace();
        }

    }

    //获取jedis对象
    @Autowired
    private JedisPool jedisPool;

    private static int count = 1;

    public void clearImg(){
        Jedis jedis = jedisPool.getResource();

        Set<String> sdiff = jedis.sdiff(RedisConstant.SETMEAL_PIC_RESOURCES, RedisConstant.SETMEAL_PIC_DB_RESOURCES);
        if (sdiff.size() > 0){
            //表 redis和七牛云存在无效图片
            System.out.println("sdiffde的无效数量为:"+sdiff.size());
            //调用工具类,将set集合转换成数组
            List<String> imgFileNames = QiniuUtils.setToArrayList(sdiff);
            //清楚七牛云中的无效图片
            for (String imgFileName : imgFileNames) {
                QiniuUtils.deleteFileFromQiniu(imgFileName);
            }
            //清楚redis中的无效图片
            String[] cleanImages = imgFileNames.toArray(new String[]{});

            jedis.srem(RedisConstant.SETMEAL_PIC_RESOURCES,cleanImages);
        }
        //释放资源
        jedis.close();
    }
}
